import { Text, View, TouchableOpacity } from "react-native";
import { Container } from "@/components/container";
{{#if (eq api "orpc")}}
import { useQuery } from "@tanstack/react-query";
import { orpc } from "@/utils/orpc";
{{/if}}
{{#if (eq api "trpc")}}
import { useQuery } from "@tanstack/react-query";
import { trpc } from "@/utils/trpc";
{{/if}}
{{#if (and (eq backend "convex") (eq auth "clerk"))}}
import { Link } from "expo-router";
import { Authenticated, AuthLoading, Unauthenticated, useQuery } from "convex/react";
import { api } from "@{{projectName}}/backend/convex/_generated/api";
import { useUser } from "@clerk/clerk-expo";
import { SignOutButton } from "@/components/sign-out-button";
{{else if (and (eq backend "convex") (eq auth "better-auth"))}}
import { useConvexAuth, useQuery } from "convex/react";
import { api } from "@{{projectName}}/backend/convex/_generated/api";
import { authClient } from "@/lib/auth-client";
import { SignIn } from "@/components/sign-in";
import { SignUp } from "@/components/sign-up";
{{else if (eq backend "convex")}}
import { useQuery } from "convex/react";
import { api } from "@{{projectName}}/backend/convex/_generated/api";
{{/if}}
{{#unless (or (eq backend "none") (and (eq backend "convex") (eq auth "better-auth")))}}
import { Ionicons } from "@expo/vector-icons";
{{/unless}}
import { Card, Chip, useThemeColor } from "heroui-native";

export default function Home() {
{{#if (eq api "orpc")}}
const healthCheck = useQuery(orpc.healthCheck.queryOptions());
{{/if}}
{{#if (eq api "trpc")}}
const healthCheck = useQuery(trpc.healthCheck.queryOptions());
{{/if}}
{{#if (and (eq backend "convex") (eq auth "clerk"))}}
const { user } = useUser();
const healthCheck = useQuery(api.healthCheck.get);
const privateData = useQuery(api.privateData.get);
{{else if (and (eq backend "convex") (eq auth "better-auth"))}}
const healthCheck = useQuery(api.healthCheck.get);
const { isAuthenticated } = useConvexAuth();
const user = useQuery(api.auth.getCurrentUser, isAuthenticated ? {} : "skip");
{{else if (eq backend "convex")}}
const healthCheck = useQuery(api.healthCheck.get);
{{/if}}
{{#unless (eq backend "none")}}
const mutedColor = useThemeColor("muted");
const successColor = useThemeColor("success");
const dangerColor = useThemeColor("danger");

{{#if (eq backend "convex")}}
const isConnected = healthCheck === "OK";
const isLoading = healthCheck === undefined;
{{else}}
{{#unless (eq api "none")}}
const isConnected = healthCheck?.data === "OK";
const isLoading = healthCheck?.isLoading;
{{/unless}}
{{/if}}
{{/unless}}

return (
<Container className="p-6">
  <View className="py-4 mb-6">
    <Text className="text-4xl font-bold text-foreground mb-2">
      BETTER T STACK
    </Text>
  </View>

  {{#unless (or (eq backend "none") (and (eq backend "convex") (eq auth "better-auth")))}}
  <Card variant="secondary" className="p-6">
    <View className="flex-row items-center justify-between mb-4">
      <Card.Title>System Status</Card.Title>
      <Chip variant="secondary" color={isConnected ? "success" : "danger" } size="sm">
        <Chip.Label>
          {isConnected ? "LIVE" : "OFFLINE"}
        </Chip.Label>
      </Chip>
    </View>
    <Card className="p-4">
      <View className="flex-row items-center">
        <View className={`w-3 h-3 rounded-full mr-3 ${ isConnected ? "bg-success" : "bg-muted" }`} />
        <View className="flex-1">
          <Text className="text-foreground font-medium mb-1">
            {{#if (eq backend "convex")}}
            Convex Backend
            {{else}}
            {{#unless (eq api "none")}}
            {{#if (eq api "orpc")}}ORPC{{else}}TRPC{{/if}} Backend
            {{/unless}}
            {{/if}}
          </Text>
          <Card.Description>
            {isLoading
            ? "Checking connection..."
            : isConnected
            ? "Connected to API"
            : "API Disconnected"}
          </Card.Description>
        </View>
        {isLoading && (
        <Ionicons name="hourglass-outline" size={20} color={mutedColor} />
        )}
        {!isLoading && isConnected && (
        <Ionicons name="checkmark-circle" size={20} color={successColor} />
        )}
        {!isLoading && !isConnected && (
        <Ionicons name="close-circle" size={20} color={dangerColor} />
        )}
      </View>
    </Card>
  </Card>
  {{/unless}}

  {{#if (and (eq backend "convex") (eq auth "clerk"))}}
  <Authenticated>
    <Card variant="secondary" className="mt-6 p-4">
      <Text className="text-foreground text-base mb-2">
        Hello {user?.emailAddresses[0].emailAddress}
      </Text>
      <Text className="text-muted text-sm mb-4">
        Private Data: {privateData?.message}
      </Text>
      <SignOutButton />
    </Card>
  </Authenticated>
  <Unauthenticated>
    <View className="mt-6 gap-4">
      <Link href="/(auth)/sign-in" asChild>
      <Text className="text-primary font-semibold">Sign in</Text>
      </Link>
      <Link href="/(auth)/sign-up" asChild>
      <Text className="text-primary font-semibold">Sign up</Text>
      </Link>
    </View>
  </Unauthenticated>
  <AuthLoading>
    <Text className="text-muted">Loading...</Text>
  </AuthLoading>
  {{/if}}

  {{#if (and (eq backend "convex") (eq auth "better-auth"))}}
  {user ? (
  <Card variant="secondary" className="p-4 mb-4">
    <View className="mb-2">
      <Text className="text-foreground text-base">
        Welcome, <Text className="font-semibold">{user.name}</Text>
      </Text>
    </View>
    <Text className="text-muted text-sm mb-4">{user.email}</Text>
    <TouchableOpacity className="bg-danger px-4 py-2 rounded-md self-start" onPress={()=> {
      authClient.signOut();
      }}
      >
      <Text className="text-danger-foreground font-medium">Sign Out</Text>
    </TouchableOpacity>
  </Card>
  ) : null}
  <Card variant="secondary" className="p-4 mb-4">
    <Text className="text-foreground font-medium mb-2">API Status</Text>
    <View className="flex-row items-center gap-2">
      <View className={`w-3 h-3 rounded-full ${healthCheck==="OK" ? "bg-success" : "bg-danger" }`} />
      <Text className="text-muted">
        {healthCheck === undefined
        ? "Checking..."
        : healthCheck === "OK"
        ? "Connected to API"
        : "API Disconnected"}
      </Text>
    </View>
  </Card>
  {!user && (
  <>
    <SignIn />
    <SignUp />
  </>
  )}
  {{/if}}
</Container>
);
}